package com.example.pagehelper;

import com.example.pagehelper.entity.User;
import com.example.pagehelper.mapper.UserMapper;
import com.example.pagehelper.util.MyBatisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * PageHelper 插件分页演示程序
 */
public class App {
    public static void main(String[] args) {
        SqlSession session = MyBatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);

        System.out.println("✅ [方式1] 正确的分页写法：");
        PageHelper.startPage(1, 5);
        List<User> users = mapper.getAllUsers();
        PageInfo<User> info1 = new PageInfo<>(users);
        printPageInfo(info1);

        System.out.println("\n❌ [方式2] 错误写法：先查询再分页（分页失效）");
        List<User> allUsers = mapper.getAllUsers(); // 查询未被分页拦截
        PageHelper.startPage(2, 5); // 无效：调用顺序错误
        PageInfo<User> info2 = new PageInfo<>(allUsers);
        printPageInfo(info2);



        session.close();
    }

    private static void printPageInfo(PageInfo<User> pageInfo) {
        System.out.println("当前页码：" + pageInfo.getPageNum());
        System.out.println("每页数量：" + pageInfo.getPageSize());
        System.out.println("总记录数：" + pageInfo.getTotal());
        System.out.println("总页数：" + pageInfo.getPages());

        for (User u : pageInfo.getList()) {
            System.out.println(u.getId() + " - " + u.getName() + " - " + u.getStatus());
        }
    }
}